package assists
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.setTimeout;
	
	import main.ClientConstants;
	
	public class ButtonUtils extends Sprite
	{
		private var _pic:DisplayObject;
		private var _text:TextField;
		private var _textStr:String;
		
		private var _callBack:Function;
		
		private var _content:Sprite;
		
		public function ButtonUtils(pic:*,callBack:Function,str:String = "")
		{
			_pic = pic;
			_callBack = callBack;
			_textStr = str;
			
			_content = new Sprite;
			this.addChild(_content);
			
			init();
		}
		
		private function init():void
		{
			_content.addChild(_pic);
			
			if(_textStr != ""){                            //如果有文本则添加本文框设置字体、文本框大小和文本位置
				_text = new TextField;
				_text.mouseEnabled = false;
				_text.multiline = true;
				_text.wordWrap = true;
				
				TextFieldUtils.setHtmlText(_text,_textStr);
				_text.width = _pic.width - 4;
				if(_text.textWidth + 4 < _pic.width - 4){
					_text.width = _text.textWidth + 4;
				}
				_text.height = _text.textHeight + 4;
				_content.addChild(_text);
				
				_text.x = (_content.width - _text.width) / 2;
				_text.y = (_content.height - _text.height) / 2;
			}
			
			_content.filters = [];
			_content.addEventListener(MouseEvent.MOUSE_DOWN,downHandler);
			_content.addEventListener(MouseEvent.MOUSE_UP,upHandler);
		}
		
		protected function upHandler(event:MouseEvent):void
		{
			_content.filters = [];
			if(_callBack is Function){
				_callBack();
			}
		}
		
		protected function downHandler(event:MouseEvent):void
		{
			_content.filters = [ClientConstants.GLOBAL_FILTER_GREY];
			
			setTimeout(function():void{ if(_content){_content.filters = [];} },1000);
		}
		
		public function changeState(bool:Boolean):void
		{
			if(bool == true){                                   //点击过此按钮
				_content.filters = [ClientConstants.GLOBAL_FILTER_WHITE];
			}else{
				_content.filters = [];
			}
		}
		
		public function clearThis():void
		{
			_content.removeEventListener(MouseEvent.MOUSE_DOWN,downHandler);
			_content.removeEventListener(MouseEvent.MOUSE_UP,upHandler);
			
			_textStr = "";
			_pic = null;
			_content = null;
		}
	}
}